package com.hfzy.ihk.web.oauth.server.controller;

import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.util.image.CaptchaUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Created by YANFA on 2019/1/25.
 */
@RestController
@RequestMapping("captcha")
public class CaptchaController {

    /**
     * 生成验证码
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        long time = System.currentTimeMillis();
        response.setDateHeader("Last-Modified", time);
        response.setDateHeader("Date", time);
        response.setDateHeader("Expires", time);

//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.IMAGE_JPEG);

        //随机生成字符串，并写入session
        String code = CaptchaUtils.getRandCode(4);

        BufferedImage image = CaptchaUtils.getImage(100,30, code, 5);

        request.getSession().removeAttribute(GlobalStatic.VALIDATE_CODE);
        request.getSession().setAttribute(GlobalStatic.VALIDATE_CODE, code);

        // 将内存中的图片通过流动形式输出到客户端
        ImageIO.write(image, "JPEG", response.getOutputStream());
        return;
    }
}
